package com.telit.android.strategy.impl;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.exceptions.ClientException;
import com.telit.android.constant.StrategyTypeConstants;
import com.telit.android.feign.UpmsFeignClient;
import com.telit.android.service.impl.UserInfoService;
import com.telit.android.strategy.SmsCodeStrategyInterface;
import com.telit.common.constant.RedisConstants;
import com.telit.common.constant.SmsTemplateConstants;
import com.telit.common.enums.ResultCode;
import com.telit.common.exception.ForestBaseException;
import com.telit.common.util.AliSmsUtils;
import com.telit.common.util.RedisUtils;
import com.telit.common.vo.user.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


/**
 * @Auther amy
 * @Describe 忘记密码短信发送校验
 */
@Service(StrategyTypeConstants.STRATEGY_TYPE_SMS_CODE_FORGET_KEY)
public class ForgetPwdStorageStrategy implements SmsCodeStrategyInterface {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UpmsFeignClient upmsFeignClient;

    @Override
    public String sendSms(String phone, String code) throws ClientException {
        // 校验手机号是否存在
        Result result = upmsFeignClient.queryUserByMobile(phone);
        if(result == null || result.getData() == null || !result.getCode().equals(ResultCode.SUCCESS.getCode())){
            throw new ForestBaseException("该手机号未绑定账号,请校验手机号是否正确");
        }

        Map<String,String> map = new HashMap<>();
        map.put("code",code);
        AliSmsUtils.sendSms(phone, JSON.toJSONString(map),SmsTemplateConstants.SMS_TEMPLATE_FORGET_PWD);
        // 存入redis
        RedisUtils.set(RedisConstants.SMS_CODE_FORGET_PWD_REDIS_SUFFIX + phone,code,RedisConstants.SMS_CODE_VALIDATE_TIME);
        return String.valueOf(result.getData());
    }

    @Override
    public void checkCode(String phone, String code,Long id) {
        String key = RedisConstants.SMS_CODE_FORGET_PWD_REDIS_SUFFIX + phone;
        userInfoService.checkSmsCode(key,code);
    }
}
